<template>
  <div class="category-details">
    <div class="cate-bg" v-if="props.from != 'gameDetail'"></div>
    <div class="content">
      <!-- 搜索区域 -->
      <div class="query">
        <nut-input v-model="queryGame" :placeholder="t('inside_page_search_placeholder')" clearable>
          <template #left>
            <iconpark-icon icon-id="sousuo" size=".8rem" class="refresh"></iconpark-icon>
          </template>
        </nut-input>
        <ImgT v-if="props.from != 'gameDetail'" :src="`/imgs/home/close.webp`" class="close_img" alt=""
          @click="handleClose" />
      </div>

      <div class="main_content" style="position: relative;">
        <!-- 箭头 -->
        <div class="arrow arrow-down" :class="showArrowDown ? '' : 'arrow-hidde'">
          <ImgT :src="`/imgs/home/arrow.png`" style="width: 16px;height: 16px;" />
        </div>
        <div class="arrow arrow-up" :class="showArrowUp ? '' : 'arrow-hidde'">
          <ImgT :src="`/imgs/home/arrow.png`" style="width: 16px;height: 16px;transform: rotate(180deg);" />
        </div>
        <!-- 左侧tab  -->
        <div class="tab" ref="scrollTabRef" id="tab_target" @scroll="scrollTab" @touchstart="touchstart"
          @touchend="touchend">
          <div ref="tabRef">
            <div v-for="(v, i) in gameTabs" :key="v.id">
              <div class="tab_level1" :key="`first${v.id}`">
                <!-- 分类详情页主分类 -->
                <div v-if="props.from == 'gameDetail'" class="tab_item tab_all" :class="{ tab_ac: state.agentId == -1 }"
                  @click="onClickTab(v, i, true)">
                  <span>全部</span>
                </div>
                <!-- 主分类 -->
                <div v-else ref="tabItem" class="tab_item" :class="{ tab_ac: tabDta.id == v.id }"
                  @click="onClickTab(v, i, true)">
                  <ImgT :key="'v.icon_h5'" :src="joinURL(settings.backend_upload, v.icon_h5)" class="tab_style" alt="" />
                  <span class="item_name">{{ v.name[lang] }}</span>
                </div>
                <div class="show_second_list"
                  :class="[{ show: threeGameKinds.length > 0 && tabDta.id == v.id && state.type == 1 && tabDta.openChild }]"
                  @click="onClickTab(v, $event, true)">
                  <iconpark-icon icon-id="xia" color="#fff" size="0.8rem"></iconpark-icon>
                </div>
              </div>
              <!-- 次级菜单 -->
              <div
                v-if="threeGameKinds.length > 0 && tabDta.id == v.id && state.type == 1 && (tabDta.openChild || props.from == 'gameDetail')"
                :key="`secondary${v.id}`" class="second_tab">
                <div v-for="(item, index) in threeGameKinds" ref="subItem" :class="{ tab_ac: state.agentId == item.id }"
                  :key="item.id" class="second_tab_item" @click="onClickSTab(item, index)">
                  <img :key="item.picture_pc" v-lazy="joinURL(settings.backend_upload, item.picture_pc)" />
                  <span>{{ item.name[lang] }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>



        <!-- 右侧数据 -->
        <!-- 电子1-捕鱼2-棋牌5  -->
        <div class="games_box" v-if="state.type == 1" @touchstart="onTouchStart" @touchmove="onTouchMove"
          @touchend="onTouchEnd">
          <nut-tabs v-model="state.lableActive" title-scroll @change="changeThirdTab($event, true)">
            <nut-tab-pane :title="unserialize(item.kind_name, true)" :pane-key="item.kindId"
              v-for="(item, i) in kindList" :key="i" :id="`pane-box${i}`">
              <PullRefresh v-if="showLeft" v-model="refresh" @refresh="refreshFun" :body="`pane-box${i}`">
                <div class="games_list-box">
                  <div style="height: 200px;" v-if="!showGames.length">
                    <EmptyState :text="queryGame ? t('inside_page_no_null_data') : ''" :tip="queryGame ? '' : ' '" />
                  </div>
                  <div class="game_list">
                    <div class="item" v-for="v in showGames" :key="`${v.agentId}-${v.venue_id}-${v.id}`">
                      <GameItem :item="v"></GameItem>
                    </div>
                  </div>
                </div>
              </PullRefresh>
            </nut-tab-pane>
          </nut-tabs>
        </div>
        <!--视讯3-体育4-彩票6 没有  二级菜单 -->
        <div class="games_box games_box2" style="overflow-y: auto;" v-if="state.type == 2">
          <div style="height: 200px;" v-if="threeGameKinds.length == 0">
            <EmptyState :text="queryGame ? t('inside_page_no_null_data') : ''" :tip="queryGame ? '' : ' '" />
          </div>
          <div class="game_list game_list1" v-else>
            <div class="item_2" v-for="(v, i) in threeGameKinds" :key="i" @click.stop="onPlayGame(v)">
              <div class="item_bg">
                <div>
                  <img :key="v.logo_h5" v-lazy="joinURL(settings.backend_upload, v.logo_h5)" class="logo_h5" />
                  <span>{{ unserialize(v.name, false) }}</span>
                </div>
                <img v-if="[3, 4].includes(state.kindId)" :key="v.picture_h5"
                  v-lazy="joinURL(settings.backend_upload, v.picture_h5)" />
                <img v-else v-lazy="`/imgs/home/dynamic_cp_logo${i}.png`" :key="i" class="logo_qipai" />
                <!-- 收藏 -->
                <iconpark-icon v-if="isLocalLoggedIn && !v.has_next" class="fav"
                  :name="allCollected.includes(v.id) ? 'shoucang-sel' : 'shoucang-def'" size="1rem"
                  @click.stop="reqCollect(v, allCollected)"></iconpark-icon>
                <!-- 热门 -->
                <div class="game_hot" v-if="v.is_hot == 1">
                  <iconpark-icon name="hot" size=".8rem"></iconpark-icon>
                  <span>HOT</span>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
    <OverLoading v-model:visible="loading"></OverLoading>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { joinURL } from '@/utils/publicMethods'
import { useI18n } from "vue-i18n";
import { ref, computed, reactive, onMounted, onBeforeUnmount, watch } from "vue"
import { Local } from "@/utils/storage";
import { Page } from "@/store/page";
import { User } from "@/store/user";
import pinia from "@/store";
import { storeToRefs } from "pinia";
import EmptyState from '../searchGames/components/EmptyState.vue'
import { unserialize, onPlayGame } from "@/utils/useStoreMethods";
import { isLocalLoggedIn } from "@/utils/commonVar";
import { repMyGamesData, reqCollect } from "@/utils/useNetMethods";
import eventBus from "@/lolo/eventBus";
import { useTouchMove } from "@/hooks/useTouchMove"
import OverLoading from "@/components/Loading.vue";
import PullRefresh from '@/components/PullRefresh.vue'
const { t } = useI18n();
const page = Page(pinia)
const { settings, lang, homeGameData, showLeft } = storeToRefs(page);
const { allCollected } = storeToRefs(User(pinia));



const props = defineProps({
  from: { // gameDetail-分类详情页
    type: [String, Number],
    default: ''
  },
  agent_id: {
    type: [String, Number],
    default: ''
  },
  venue_id: {
    type: [String, Number],
    default: ''
  },
  has_next: {
    type: [String, Number],
    default: ''
  },
  name: {
    type: [String, Number],
    default: ''
  }
})
const loading = ref(true);


const first = {
  kind_name: '{"zh-CN":"全部","vi-VN":"tất cả","en-US":"All"}',
  kindId: 0,
  key: 0,
  icon_after: "/img/game/all_un.webp",
  icon_before: "/img/game/all.webp",
};
const first_hot = {
  kind_name: '{"zh-CN":"热门","vi-VN":"Phổ biến","en-US":"Popular"}',
  kindId: 0,
  key: 0,
  icon_after: "/img/game/all_un.webp",
  icon_before: "/img/game/all.webp",
};
const last = [
  {
    kind_name: '{"zh-CN":"最近","vi-VN":"gần đây","en-US":"Recent"}',
    kindId: -3,
    key: 2,
    icon_after: "/img/game/zuijin_un.webp",
    icon_before: "/img/game/zuijin.webp",
  },
  {
    kind_name: '{"zh-CN":"收藏","vi-VN":"Yêu thích","en-US":"Favorites"}',
    kindId: -2,
    key: 3,
    icon_after: "/img/game/shoucang_un.webp",
    icon_before: "/img/game/shoucang.webp",
  },
];

// 左侧滑动顶部和底部的判断
const toTop = ref(false)
const toBottom = ref(false)
let topTimeout: any = null
let bottomTimeout: any = null
// 左侧箭头
const showArrowDown = ref(false)
const showArrowUp = ref(false)
const scrollTabRef = ref()
const tabRef = ref()
const refresh = ref(false)
const scrollTab = () => {
  if (!scrollTabRef.value || !tabRef.value) return
  if (scrollTabRef.value.scrollTop > 50) { // 显示上边的箭头
    showArrowUp.value = true
  } else {
    showArrowUp.value = false
  }
  if ((tabRef.value.clientHeight - scrollTabRef.value.scrollTop - scrollTabRef.value.clientHeight) < 40) { // 显示下边的箭头
    showArrowDown.value = false
  } else {
    showArrowDown.value = true
  }
  // 到顶部的判断
  if (topTimeout) clearTimeout(topTimeout)
  if (scrollTabRef.value.scrollTop == 0) { // 到顶部了
    topTimeout = setTimeout(() => {
      toTop.value = true
    }, 500)
  } else {
    toTop.value = false
  }
  // 到底部的判断
  if (bottomTimeout) clearTimeout(bottomTimeout)
  if ((tabRef.value.clientHeight - scrollTabRef.value.scrollTop - scrollTabRef.value.clientHeight) < 0) {
    bottomTimeout = setTimeout(() => {
      toBottom.value = true
    }, 500)
  } else {
    toBottom.value = false
  }
}

let touchStartY = 0
const touchstart = (e: any) => {
  touchStartY = e.changedTouches[0].clientY
}
const touchend = (e: any) => {
  if (touchStartY > (e.changedTouches[0].clientY + 40)) {
    if (toBottom.value) {
      // 切换到下一个分类
    }
  }
  if (touchStartY < (e.changedTouches[0].clientY - 40)) {
    if (toTop.value) {
      // 切换到上一个分类
    }
  }
}

const queryGame = ref(""); // 搜索内容
const state = reactive({
  // 游戏平台id  -1为查看全部的游戏
  agentId: -1,

  // //也表示场馆id
  kindId: 1,

  // 游戏类型
  type: 1,

  // 右上方侧标签点击样式
  lableActive: 0,
});

const tabDta: any = ref({}); // 当前tab
const gameTabs: any = computed(() => { // 左侧导航
  if (props.from == 'gameDetail') { // 分类详情页的左侧导航
    return [homeGameData.value.find((e: any) => e.id == Number(props.venue_id)) || {}]
  }
  return homeGameData.value.filter((e: any) => e.id > 0);
})

// 切换3级tab
const changeThirdTab = (a: any, handle?: any) => {
  state.lableActive = Number(a.paneKey)
  if (handle === true) {
    sessionStorage.setItem('menu_ttab', a.paneKey)
  }
}
if (props.from != 'gameDetail') {
  try {
    const obj: any = sessionStorage.getItem('menu_ttab') || ''
    if (obj) {
      setTimeout(() => {
        changeThirdTab({ paneKey: Number(obj) })
      }, 500)
    }
  } catch { }
}

// 二级菜单
const threeGameKinds = computed(() => {
  const platform: any = gameTabs.value.find((a: any) => a.id == Number(state.kindId))
  if (!platform) return []
  return (platform.three_platform || []).filter((item: any) => unserialize(item.name, false))
})
// 点击tab
const tabItem: any = ref([])
const onClickTab = (v: any, i: any, handle: any) => {
  if (handle === true) {
    sessionStorage.setItem('menu_tab', JSON.stringify({
      v: v,
      i: i
    }))
  }

  if (![3, 4, 6].includes(v.id)) {
    state.type = 1;
    setTimeout(() => {
      if (tabItem.value[i]) {
        tabItem.value[i].scrollIntoView(true);
      }
    }, 100)
  } else {
    state.type = 2;
  }
  tabDta.value = v;
  state.agentId = -1;
  state.kindId = v.id;

  setTimeout(() => {
    if (scrollTabRef.value) {
      scrollTab()
    }
  }, 300)

  if (props.from == 'gameDetail') return
  // 开关子元素列表
  const open = !(tabDta.value.openChild)
  gameTabs.value.forEach((item: any) => {
    item.openChild = false
  })
  if (![3, 4, 6].includes(v.id)) {
    tabDta.value.openChild = open
  }
};
if (gameTabs.value[0]) {
  onClickTab(gameTabs.value[0], 0, false)
  setTimeout(() => {
    gameTabs.value[0].openChild = false
  }, 0)
}

if (props.from != 'gameDetail') {
  try {
    const obj: any = JSON.parse(sessionStorage.getItem('menu_tab') || '{}')
    if (obj.v) {
      setTimeout(() => {
        onClickTab(obj.v, obj.i, false)
      }, 100)
    }
  } catch { }
}

const refreshFun = () => {
  refresh.value = true;
  refreshMyGames();
};

// 点击厂商切换游戏
const subItem: any = ref([])
const onClickSTab = (v: any, index: any) => {
  sessionStorage.setItem('menu_stab', JSON.stringify({
    v: v,
    index: index
  }))
  state.lableActive = 0;
  state.agentId = v.id;
  setTimeout(() => {
    if (subItem.value[index]) {
      subItem.value[index].scrollIntoView({
        behavior: "smooth",
        block: "center"
      });
    }
  }, 100)
};

if (props.from == 'gameDetail') {
  if (props.agent_id) {
    const i = threeGameKinds.value.findIndex((a: any) => a.id == Number(props.agent_id))
    onClickSTab({ id: Number(props.agent_id) }, i)
  } else {
    onClickSTab({ id: -1 }, 0)
  }
} else {
  try {
    const obj: any = JSON.parse(sessionStorage.getItem('menu_stab') || '{}')
    if (obj.v) {
      setTimeout(() => {
        onClickSTab(obj.v, obj.index)
      }, 300)
    }
  } catch { }
}

// 右侧标签
const kindList: any = computed(() => {
  if (state.agentId == -1) return [first_hot, ...last]
  return [first, ...last]
})
// 游戏集合
const list = computed(() => {
  const platform: any = gameTabs.value.find((a: any) => a.id == Number(state.kindId))
  if (!platform) return []
  let allgames = platform.three_platform
  if (state.agentId !== -1) {
    allgames = allgames.filter((item: any) => item.id === state.agentId);
  }
  const games: any = []
  allgames.flatMap((item: any) => {
    if (item.three_game_kind) {
      item.three_game_kind.flatMap((kind: any) => {
        kind.three_game.filter((game: any) => {
          games.push(game)
        })
      })
    }
  });
  if (state.agentId === -1 && state.lableActive == 0) {
    return games.filter((item: any) => item.is_hot == 1);
  }
  return games
})

// 最近的游戏
const nearList: any = ref([])
// 收藏的游戏
const starList: any = ref([])
const refreshMyGames = (d: any) => {
  if (d == 'clear') {
    nearList.value = []
    starList.value = []
  }
  repMyGamesData(() => {
    refresh.value = false;
  })
}
const handleMyGames = (res: any) => {
  nearList.value = res.recently
  starList.value = res.collected
  User(pinia).getCollected(res.collected);
}

// 展示的游戏
const showGames: any = computed(() => {
  let arr = []
  if (state.lableActive == 0) {
    arr = list.value
  }
  if (state.lableActive == -3) {
    arr = list.value.filter((itm: any) => {
      return nearList.value.includes(itm.id)
    });
  }
  if (state.lableActive == -2) {
    arr = list.value.filter((itm: any) => {
      return starList.value.includes(itm.id)
    });
  }
  // 去重
  arr = Array.from(new Map(arr.map((item: any) => [item.id, item])).values());
  return arr.filter((item: any) => unserialize(item.name, false).includes(queryGame.value))
})


// 手动设置激活的分类
const setCateVal = (item: any) => {
  const i = gameTabs.value.findIndex((a: any) => a.id == item.id)
  onClickTab(item, i, true)
}
// 手动设置激活的二级分类
const setSubCateVal = (id: any) => {
  const target = tabDta.value.three_platform.findIndex((a: any) => a.id == id)
  if (target > -1) {
    onClickSTab(tabDta.value.three_platform[target], target)
    tabDta.value.openChild = true
  }
}


const beforeBack = () => {
  if (showLeft.value) {
    history.pushState(null, '', window.location.href);
    handleClose()
  }
}

watch(() => showLeft.value, (nv) => {
  if (nv) {
    document.body.classList.add('no_scroll')
  } else {
    document.body.classList.remove('no_scroll')
  }
})

onMounted(() => {
  refreshMyGames('clear')
  eventBus.on("msg_notify_req_my_games", handleMyGames);
  eventBus.on("msg_notify_modify_collect", refreshMyGames);
  eventBus.on('setCateVal', setCateVal)
  eventBus.on('setSubCateVal', setSubCateVal)
  setTimeout(() => {
    if (scrollTabRef.value) {
      scrollTab()
    }
  }, 300)

  setTimeout(() => {
    loading.value = false
  }, 500)
  if (showLeft.value) {
    document.body.classList.add('no_scroll')
  }
  window.addEventListener('popstate', beforeBack);
})
onBeforeUnmount(() => {
  eventBus.off('msg_notify_req_my_games', handleMyGames);
  eventBus.off('msg_notify_modify_collect', refreshMyGames);
  eventBus.off('setCateVal', setCateVal)
  document.body.classList.remove('no_scroll')
  window.removeEventListener('popstate', beforeBack)
})


const onSwipeRight = () => {
  const index = kindList.value.findIndex((item: any) => item.kindId === Number(state.lableActive))
  if (index >= 1) {
    changeThirdTab({
      paneKey: kindList.value[index - 1]?.kindId
    })
  } else {
    // 退出页面
    // handleClose()
  }
}

const onSwipeLeft = () => {
  const index = kindList.value.findIndex((item: any) => item.kindId === Number(state.lableActive))
  if (index < kindList.value.length - 1) {
    changeThirdTab({
      paneKey: kindList.value[index + 1]?.kindId
    })
  }
}

// @ts-ignore
const { onTouchEnd, onTouchMove, onTouchStart } = useTouchMove(100, {
  onSwipeLeft,
  onSwipeRight
})

const handleClose = () => { // 关闭
  setTimeout(() => {
    page.setShowLeft(false)
  }, 0)
  Local.remove('homePageData')
  sessionStorage.setItem('menu_tab', '{}')
  sessionStorage.setItem('menu_stab', '{}')
  sessionStorage.setItem('menu_ttab', '')
}
</script>

<style scoped lang="scss">
@use './index.scss';
</style>
